package com.wyl.template.filter;

import com.wyl.template.constant.AppConstants;
import com.wyl.template.util.IDUtil;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @Auther: wyl
 * @Date: 2021/4/28
 * @Description: TraceId过滤器
 * 用来添加到日志中，追踪调用链路
 */
@WebFilter(urlPatterns = "/*")
@Order(1)
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 尝试从请求信息中获取TraceId信息
        String traceId = servletRequest.getParameter(AppConstants.TRACE_ID);

        // 为空设置默认值
        if (!StringUtils.hasText(traceId)) {
//            traceId = UUID.randomUUID().toString();
            traceId = IDUtil.getID();
        }
        // 在MDC中放入traceId
        MDC.put(AppConstants.TRACE_ID, traceId);

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
